﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Dispatch.Receive
{
    /// <summary>
    /// AGV侦听
    /// </summary>
    internal class AgvListener
    {
        bool isEnd;
        Thread? th;
        int _port;


        internal void Start(int port)
        {
            _port = port;
            isEnd = true;
            th = new Thread(UdpEvent);
            th.IsBackground = true;
            th.Start();
        }

        /// <summary>
        /// udp侦听
        /// </summary>
        void UdpEvent()
        {
            UdpClient udpClient = new UdpClient(_port);
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 0);
            while (isEnd)
            {
                try
                {
                    byte[] buffer = udpClient.Receive(ref iPEndPoint);
                    string ip = iPEndPoint.Address.ToString();
                    AgvReceiveData? receiveData = AgvEvent.ResolveData( buffer);
                    if (receiveData != null)
                    {
                        new DispatchAgv().Dispatch(receiveData.Value);

                    }

                }
                catch(Exception e){
                    string m = e.Message;
                }
            }
            udpClient.Close();
        }

        internal void Dispose()
        {
            isEnd = true;
            if (th != null && th.IsAlive)
            {
                th.Interrupt();
            }
            th = null;
        }

    }
}
